Can we use a minus operator as a Comparison Operator ?
I couldn't find like a this situtation.
function sign(x) {
return (x > 0) - (x < 0) || +x;
}
It will not act as a comparisons operator. It will act as a math operator. To this work, JavaScript converts the boolean resulting from the x > 0 and x < 0 to zero or one, then do the subtraction.
This is a weird code, but valid.
There are two steps to describe here.
As already noted in Elia Soares's answer, JavaScript implicitly converts boolean expression to numbers when doing a subtraction. true will be converted to 1, and false to 0.
console.log(+true);
console.log(+false);
let x = 20;
console.log(+(x > 0));
console.log(+(x < 0));
then, doing (x > 0) - (x < 0) means:
If x is positive, we get 1 - 0, which gives 1.
If x is negative, we get 0 - 1, which gives -1.
If x is zero, we get 0 - 0, which gives 0.
This looks already good to create a sign(x) function as usually expected.
However, also consider undefined in this formula: any comparisons will give false, and so the above subtraction will give zero.
That's a bit dangerous, could be that you forgot to assign a value to the variable, which is a common bug when you write code.
That's why the || +x was added.
|| in javascript means:
Evaluate the left side. If it's truthy, return the left side. Otherwise, return the right side.
+1, and -1 are truthy, and 0 is falsy, so the full expression (x > 0) - (x < 0) || +x will evaluate to +x if and only if the subtraction gives zero.
If x is zero, this will still give +0 which is 0.
If x is null, this will give +null which is 0.
If x is undefined, this will give +undefined which is NaN.
Getting a NaN in your calculation will quickly cause all your subsequent results to be NaN, warning you that there was something undefined that you probably forgot.
Note that the +x still evaluate to 0 if x is null er empty string '', so this code won't change the (mayybe unexpected) result zero for those special cases.